package com.cuit.controller;

import com.cuit.pojo.Doctor;
import com.cuit.pojo.Manger;
import com.cuit.pojo.Page;
import com.cuit.service.Impl.MangerServiceImpl;
import com.cuit.service.MangerService;
import com.cuit.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/mangerServlet")
public class MangerServlet extends BaseServlet {
    private MangerService mangerService = new MangerServiceImpl();

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Manger loginManger = mangerService.login(new Manger(username, password));
        if (loginManger == null) {
            req.setAttribute("msg", "用户名或密码错误!");
            req.setAttribute("username", username);
            req.getRequestDispatcher("/pages/manager/managerindex.jsp").forward(req, resp);
        } else {
            req.getSession().setAttribute("user", loginManger);
            req.getRequestDispatcher("/mangerServlet?action=page").forward(req, resp);
        }
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Doctor> page = mangerService.queryDoctorByPage(pageNo, pageSize);
        page.setUrl("/hospital/mangerServlet?action=page");
        req.setAttribute("page", page);
        req.getRequestDispatcher("/pages/manager/manager-dc.jsp").forward(req, resp);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        mangerService.add();
        req.getRequestDispatcher("/mangerServlet?action=page").forward(req, resp);
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        if (id == 0) {
            req.setAttribute("msg", "id有误");
        }
        mangerService.delete(id);
        req.getRequestDispatcher("/mangerServlet?action=page").forward(req, resp);
    }
}
